import React, { Component } from 'react'
import { Card, Breadcrumb, Form, Radio, Button, DatePicker, Space, Table, Tag, Modal } from 'antd'
import { EditOutlined, DeleteOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import { Link } from 'react-router-dom'
import { article } from 'api/article'
import { deleteArticleList, getArticleInfo } from 'api/articles'
import defaultImg from 'assets/error.png'
import Channel from 'components/Channel.js';
const { confirm } = Modal;
const { RangePicker } = DatePicker;

export default class ArticleList extends Component {
  reqParams = {
    // 获取文章列表的参数对象，这种不用于渲染的数据最好不要定义在state里面
    page: 1,
    per_page: 10
  }
  columns = [
    {
      title: '封面',
      render(data) {
        if (data.cover.type === 0) {
          // 说明没有封面
          return <img src={defaultImg} alt="" style={{ width: 200, height: 125, objectFit: 'cover' }} />
        } else {
          return <img src={data.cover.images[0]} alt="" style={{ width: 200, height: 125, objectFit: 'cover' }} />
        }
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        const obj = article.find((item) => item.id === status)
        return <Tag color={obj.color}>{obj.name}</Tag>
      }
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (data) => {
        // 放两个按钮
        return (
          <Space>
            <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={() => { this.modifyArticle(data.id) }} />
            <Button danger type="primary" onClick={() => { this.deleteArticle(data.id) }} shape="circle" icon={<DeleteOutlined />} />
          </Space>
        )
      }
    },
  ];
  state = {
    articles: {} // 文章列表数据
  }
  render() {
    // console.log(this.props);
    const { total_count, results, page, per_page } = this.state.articles
    return (
      <div>
        <Card title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to='/home'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }>
          <Form initialValues={{ status: -1 }} onFinish={this.onFinish}>
            <Form.Item label='状态' name='status'>
              <Radio.Group>
                {
                  article.map(item => <Radio key={item.id} value={item.id}>{item.name}</Radio>)
                }
              </Radio.Group>
            </Form.Item>
            <Form.Item label='频道' name='channel_id'>
              <Channel></Channel>
            </Form.Item>
            <Form.Item label='日期' name='date'>
              <RangePicker />
            </Form.Item>
            <Form.Item>
              <Button type='primary' htmlType='submit'>筛选</Button>
            </Form.Item>
          </Form>
        </Card>
        <Card title={`已为您筛选出了${total_count}条数据`}>
          {/* 表格 */}
          <Table
            columns={this.columns}
            dataSource={results}
            rowKey='id'
            pagination={{
              position: ['bottomCenter'],
              total: total_count,
              current: page,
              pageSize: per_page,
              onChange: this.onChange
            }} />
        </Card>
      </div >
    )
  }
  // 修改文章
  modifyArticle = (id) => {
    // console.log(id);
    this.props.history.push(`/home/publish/${id}`)
  }
  // 分页的change事件
  onChange = (page, pageSize) => {
    // 修改数据，把新的数据赋值给参数对象，然后重新发请求
    this.reqParams.page = page
    this.reqParams.per_page = pageSize
    // 调用发请求的函数
    this.getArticleInfo()
  }
  // 收集表单数据
  onFinish = (values) => {
    // console.log(values);
    // 收集到的表单数据，解构出来方便使用
    const { status, channel_id, date } = values
    // 判断传递的状态
    if (status !== -1) {
      // 说明不是全部，所以就给请求的参数对象添加status属性
      this.reqParams.status = status
    } else {
      // 否则就删除这个属性
      delete this.reqParams.status
    }
    // 判断传递的channel_id
    if (channel_id !== undefined) {
      // 因为channel_id里面有值为0所以判断是否为undefined
      // 如果没有undefined，则说明传递值
      this.reqParams.channel_id = channel_id
    } else {
      // 否则就删除这个属性
      delete this.reqParams.channel_id
    }
    // 判断传递的日期参数
    if (date) {
      // 说明传递日期了
      this.reqParams.begin_pubdate = date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss')
      this.reqParams.end_pubdate = date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss')
    } else {
      delete this.reqParams.begin_pubdate
      delete this.reqParams.end_pubdate
    }
    // 收集完所有的数据之后然后发请求，但是在发请求之前得把页码设置为1，因为是重新搜索文章
    this.reqParams.page = 1
    // console.log(this.reqParams);
    this.getArticleInfo()
  }
  // 获取文章列表数据
  async getArticleInfo() {
    const res = await getArticleInfo(this.reqParams)
    // console.log(res);
    this.setState({
      articles: res.data
    })
  }
  // 删除文章
  deleteArticle = (data) => {
    // 弹窗是否确定删除
    confirm({
      title: '删除提示',
      icon: <ExclamationCircleFilled />,
      content: '确定删除这篇文章吗？',
      onOk: async () => {
        // console.log('OK');
        // 调接口发请求删除
        await deleteArticleList(data)
        // 调用获取文章的接口重新渲染文章
        this.getArticleInfo()
      }
    });
  }
  componentDidMount() {
    this.getArticleInfo()
  }
}
